package cn.pugle.mianshi.thread1To10;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * 跑它几百万次, 也没出bug, 不代表没有bug?
 *
 * <p> Created by tzp on 2017/9/6.
 */
@SuppressWarnings({"Duplicates", "AlibabaRemoveCommentedCode"})
public class PrintToTen3a implements Runnable {
    private int count = 1;
    private List<Integer> results = new ArrayList<>(120);

    @Override
    public void run() {
        Thread thread1 = new Thread(() -> {
            int myCt = 0;
            while (count <= MAX) {
                if (count % 2 == 0 && count <= MAX) {//这里再判一次, 就不会打印101了
                    //"打印, 自增" 这个写法就没有1324问题了
                    results.add(count);
                    count++;
                    myCt++;
                }
                Thread.yield();
            }
            assert myCt == 50;
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            int myCt = 0;
            while (count <= MAX) {
                if (count % 2 == 1 && count <= MAX) {
                    results.add(count);
                    count++;
                    myCt++;
                }
                Thread.yield();
            }
            assert myCt == 50;
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<Integer> expect = new ArrayList<>(120);
        for (int i = 1; i <= MAX; i++) {
            expect.add(i);
        }
        assert Arrays.equals(results.toArray(), expect.toArray());
    }

    public static void main(String[] args) {
        new PrintToTen3a().run();
    }
}
